/*
* @Author: steven.wang
* @Date:   2018-12-26 16:35:53
* @Last Modified by:   steven.wang
* @Last Modified time: 2019-03-21 11:14:23
*/
const fs = require("fs");
const superagent = require('superagent');
const cheerio = require('cheerio');
const asyncQuene = require("async").queue;
require('superagent-charset')(superagent);
const query = require('./db');

/**
 * 异步获取页面属性
 * @author   steven.wang
 * @DateTime 2018-12-26T16:05:57+0800
 * @param    {string}                 url 链接
 * @return   {Promise}
 */
const getHtmlAsync = (url, charset = 'utf-8') => {
	return new Promise((resolve, reject) => {
		superagent.get(url)
            .buffer()
            .charset(charset)
            .set({'accept-encoding': 'gzip'})
            .then(res => {
			if (res.ok) {
				resolve(cheerio.load(res.text))
			} else {
				reject(res.err);
			}
		}, err => {
			reject(err);
		});
	});
}
/**
 * 将画册信息保存为JSON
 * @author steven.wang
 * @DateTime 2019-02-27T11:04:44+0800
 */
const writeJsonToFile = (path, data) => {
    try {
        fs.writeFileSync(path, JSON.stringify(data));
    } catch(e) {
        // statements
        throw new Error('写入' + path + '失败');
    }
}
/**
 * 下载画册里面的所有图片
 * @author steven.wang
 * @DateTime 2019-02-27T11:05:09+0800
 */
const downloadImg = albumList => {
    console.log('Start download album`s image ....');
    const folder = `img-${config.currentImgType}-${config.startPage}-${config.endPage}`;
    fs.mkdirSync(folder);
    let downloadCount = 0;
    let q = asyncQuene(function ({ title: albumTile, url: imageUrl }, cb) {
        request.get(imageUrl).end(function (err, res) {
            if (err) {
                cb ? cb() : '';
            } else {
                fs.writeFile(`./${folder}/${albumTile}-${++downloadCount}.jpg`, res.body, function (err) {
                    err ? console.log(err) : console.log(`${albumTile}保存${downloadCount}张`);
                    cb ? cb() : '';
                });
            }
        });
    }, config.downloadConcurrent);
    /**
     * 监听：当所有任务都执行完以后，将调用该函数
     */
    q.drain = function () {
        console.log('All img download');
    }

    let imgListTemp = [];
    albumList.forEach(function ({ title, imgList }) {
        imgList.forEach(function (url) {
            imgListTemp.push({ title: title, url: url });
        });
    });
    q.push(imgListTemp);//将所有任务加入队列
}
/**
 * 图片信息存入数据库
 * @author steven.wang
 * @DateTime 2019-02-27T11:02:33+0800
 */
const insertPhoto = values => {
    return query('insert into photo (type, fr, name, url, thumbnail) values ?', [values]);
}

const msleep = n => {
    Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n);
}
const sleep = n => {
    msleep(n*1000);
}

module.exports = {
	getHtmlAsync,
	writeJsonToFile,
	downloadImg,
	insertPhoto,
    sleep
}